<?php

namespace addons\sdsms\library;

class Sdsms
{
    private $_params = [];
    protected $error = '';
    protected $config = [];
    protected static $instance = null;
    protected $statusStr = array(
        "0"  => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );

    public function __construct($options = [])
    {
        if ($config = get_addon_config('sdsms')) {
            $this->config = array_merge($this->config, $config);
        }
        $this->config = array_merge($this->config, is_array($options) ? $options : []);
    }

    /**
     * 单例
     * @param array $options 参数
     * @return Sdsms
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    /**
     * 立即发送短信
     *
     * @return boolean
     */
    public function send()
    {
        $this->error = '';
        $params = $this->_params();
        $postArr = array(
            'appid' => $params['appid'],
            'signature' => $params['signature'],
            'to' => $params['mobile'],
            'project' => $params['project'],
	        'vars' => $params['vars'],
        );
        $result = \fast\Http::sendRequest('https://api.mysubmail.com/internationalsms/xsend.json', $postArr, 'POST');
        if($result['ret']) {
        	$res = json_decode($result['msg'], true);
	        if (isset($res['status']) && $res['status'] == 'success') {
		        return TRUE;
	        } else {
		        $this->error = isset($res['msg']) ? $res['msg'] : 'error';
	        }
        } else {
        	$this->error('send error');
        }
        return FALSE;
    }

    private function _params()
    {
        return array_merge([
	        'appid' => $this->config['appid'],
	        'signature' => $this->config['signature'],
	        'project' => $this->config['project'],
        ], $this->_params);
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 接收手机
     * @param   string $mobile 手机号码
     * @return Sdsms
     */
    public function mobile($mobile = '')
    {
    	if(strlen($mobile) == 10){
    		$mobile = ltrim($mobile, '0');
	    }
        $this->_params['mobile'] = '+84'.$mobile;
        return $this;
    }

	
	/**
	 * 短信内容
	 * @param   string $msg 短信内容
	 * @return Sdsms
	 */
	public function setvars($code)
	{
		$this->_params['vars'] ='{"code":"'.$code.'"}';
		return $this;
	}
}